<template>
  <view class="portrait-camera-page">
    <XenPortraitCamera
      :title="pageTitle"
      :guide-text="guideText"
      :max-size="maxSize"
      @success="handleCameraSuccess"
      @cancel="handleCameraCancel"
      @error="handleCameraError"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import XenPortraitCamera from "@/components/XenPortraitCamera.vue";
import { uploadImage } from "@/utils/unirequest";

// 页面参数
const fieldKey = ref<string>("");
const fieldLabel = ref<string>("");
const maxSize = ref<number>(5);

// 计算属性
const pageTitle = computed(() => {
  return fieldLabel.value ? `拍摄${fieldLabel.value}` : "拍摄照片";
});

const guideText = computed(() => {
  return fieldLabel.value
    ? `请将人像对准引导框拍摄${fieldLabel.value}`
    : "请将人像对准引导框";
});

// 页面加载时获取参数
onLoad((options: any) => {
  if (options) {
    fieldKey.value = options.fieldKey || "";
    fieldLabel.value = options.fieldLabel
      ? decodeURIComponent(options.fieldLabel)
      : "";
    maxSize.value = options.maxSize ? parseInt(options.maxSize) : 5;
  }

  console.log("相机页面参数:", {
    fieldKey: fieldKey.value,
    fieldLabel: fieldLabel.value,
    maxSize: maxSize.value,
  });
});

// 拍照成功处理
const handleCameraSuccess = async (result: { path: string; size: number }) => {
  console.log("拍照成功:", result);

  uni.showLoading({ title: "上传中..." });

  try {
    // 上传图片
    const fileId = await uploadImage(result.path);
    console.log("上传成功，文件ID:", fileId);

    // 通过事件总线返回结果
    uni.$emit("portrait-camera-result", {
      success: true,
      fieldKey: fieldKey.value,
      fieldLabel: fieldLabel.value,
      fileId: fileId,
      path: result.path,
      size: result.size,
    });

    uni.hideLoading();

    uni.showToast({
      title: "上传成功",
      icon: "success",
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      },
    });
  } catch (error) {
    console.error("上传失败:", error);
    uni.hideLoading();

    uni.showToast({
      title: "上传失败，请重试",
      icon: "none",
    });
  }
};

// 取消处理
const handleCameraCancel = () => {
  console.log("取消拍照");
  uni.navigateBack();
};

// 错误处理
const handleCameraError = (error: any) => {
  console.error("相机错误:", error);

  uni.showToast({
    title: "相机功能异常",
    icon: "none",
  });

  setTimeout(() => {
    uni.navigateBack();
  }, 2000);
};
</script>

<style lang="scss" scoped>
.portrait-camera-page {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
</style>
